{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Concatenate all files\n",
    "\n",
    "```bash\n",
    "$ cd path/to/train-easy/\n",
    "$ find -name '*.txt' -exec cat {} \\; > ../../../interim/train-easy_all.txt\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load libraries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The autoreload extension is already loaded. To reload it, use:\n",
      "  %reload_ext autoreload\n"
     ]
    }
   ],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.0.0-alpha0\n",
      "GPU Available:  True\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "from pathlib import Path\n",
    "import glob\n",
    "import pickle\n",
    "import json\n",
    "import matplotlib.pyplot as plt\n",
    "from lstm import LSTM_Simple\n",
    "from metrics import exact_match_metric\n",
    "from callbacks import NValidationSetsCallback, GradientLogger\n",
    "from generator import DataGenerator, DataGeneratorSeq\n",
    "\n",
    "from sklearn.model_selection import train_test_split\n",
    "import tensorflow as tf\n",
    "from tensorflow.keras.optimizers import Adam\n",
    "print(tf.__version__)\n",
    "print(\"GPU Available: \", tf.test.is_gpu_available())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load settings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "settings_path = Path('../../settings/settings.json')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(str(settings_path), 'r') as file:\n",
    "    settings_dict = json.load(file)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'batch_size': 1024,\n",
       " 'data_path': '/storage/git/deep-math/data/raw/v1.0/',\n",
       " 'epochs': 1,\n",
       " 'latent_dim': 2048,\n",
       " 'math_module': 'arithmetic',\n",
       " 'save_path': '/artifacts/',\n",
       " 'thinking_steps': 16,\n",
       " 'train_level': 'easy'}"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "settings_dict"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load data\n",
    "\n",
    "Start with batching a single file before tackling the whole dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "extrapolate  interpolate  train-easy  train-hard  train-medium\r\n"
     ]
    }
   ],
   "source": [
    "raw_path = Path(settings_dict['data_path'])\n",
    "!ls {raw_path}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "algebra__linear_1d.txt\r\n",
      "algebra__linear_1d_composed.txt\r\n",
      "algebra__linear_2d.txt\r\n",
      "algebra__linear_2d_composed.txt\r\n",
      "algebra__polynomial_roots.txt\r\n"
     ]
    }
   ],
   "source": [
    "interpolate_path = raw_path/'interpolate'\n",
    "!ls {interpolate_path} | head -5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "algebra__polynomial_roots_big.txt\r\n",
      "arithmetic__add_or_sub_big.txt\r\n",
      "arithmetic__add_sub_multiple_longer.txt\r\n",
      "arithmetic__div_big.txt\r\n",
      "arithmetic__mixed_longer.txt\r\n"
     ]
    }
   ],
   "source": [
    "extrapolate_path = raw_path/'extrapolate'\n",
    "!ls {extrapolate_path} | head -5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "algebra__linear_1d.txt\r\n",
      "algebra__linear_1d_composed.txt\r\n",
      "algebra__linear_2d.txt\r\n",
      "algebra__linear_2d_composed.txt\r\n",
      "algebra__polynomial_roots.txt\r\n"
     ]
    }
   ],
   "source": [
    "train_easy_path = raw_path/'train-easy/'\n",
    "!ls {train_easy_path} | head -5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [],
   "source": [
    "def concatenate_texts(path, pattern):\n",
    "    file_paths = list(path.glob('{}*.txt'.format(pattern)))\n",
    "    \n",
    "    input_texts = []\n",
    "    target_texts = []\n",
    "\n",
    "    for file_path in file_paths:\n",
    "        with open(str(file_path), 'r', encoding='utf-8') as f:\n",
    "            lines = f.read().split('\\n')[:-1]\n",
    "\n",
    "        input_texts.extend(lines[0::2])\n",
    "        target_texts.extend(['\\t' + target_text + '\\n' for target_text in lines[1::2]])\n",
    "        \n",
    "    return input_texts, target_texts"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Data settings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [],
   "source": [
    "math_module = settings_dict[\"math_module\"]\n",
    "train_level = settings_dict[\"train_level\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [],
   "source": [
    "datasets = {\n",
    "    'train':(raw_path, 'train-' + train_level + '/' + math_module),\n",
    "    'interpolate':(interpolate_path, math_module),\n",
    "    'extrapolate':(extrapolate_path, math_module)\n",
    "           }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Length of set interpolate is 90000\n",
      "Length of set train is 5999994\n",
      "Length of set extrapolate is 60000\n",
      "CPU times: user 2.53 s, sys: 816 ms, total: 3.35 s\n",
      "Wall time: 3.39 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "input_texts = {}\n",
    "target_texts = {}\n",
    "\n",
    "for k, v in datasets.items():\n",
    "    input_texts[k], target_texts[k] = concatenate_texts(v[0], v[1])\n",
    "    print('Length of set {} is {}'.format(k, len(input_texts[k])))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Sample:**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INPUT: What is 2 - (1 + -5) - 11?\n",
      "OUTPUT: -5\n"
     ]
    }
   ],
   "source": [
    "print('INPUT:', input_texts['train'][42])\n",
    "print('OUTPUT:', target_texts['train'][42].strip())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Concatenate texts to get text metrics (max length, number of unique tokens, etc.):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [],
   "source": [
    "all_input_texts = sum(input_texts.values(), [])\n",
    "all_target_texts = sum(target_texts.values(), [])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [],
   "source": [
    "input_characters = set(''.join(all_input_texts))\n",
    "target_characters = set(''.join(all_target_texts))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of samples: 6149994\n",
      "number of tokens: 56\n",
      "max sequence length: 188\n"
     ]
    }
   ],
   "source": [
    "tokens = sorted(list(input_characters | target_characters))\n",
    "num_tokens = len(tokens)\n",
    "max_seq_length  = max([len(txt_in) + len(txt_out) for txt_in, txt_out in zip(all_input_texts,all_target_texts)])\n",
    "\n",
    "print('Number of samples:', len(all_input_texts))\n",
    "print('number of tokens:', num_tokens)\n",
    "print('max sequence length:', max_seq_length)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Delete all texts to realease memory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [],
   "source": [
    "del all_input_texts\n",
    "del all_target_texts"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create train test splits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "input_texts_train, input_texts_valid, target_texts_train, target_texts_valid = train_test_split(input_texts['train'], target_texts['train'], test_size=0.2, random_state=42)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of training samples: 4799995\n"
     ]
    }
   ],
   "source": [
    "print('Number of training samples:', len(input_texts_train))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of validation samples: 1199999\n"
     ]
    }
   ],
   "source": [
    "print('Number of validation samples:', len(input_texts_valid))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Process text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Vectorise the text\n",
    "Before training, we need to map strings to a numerical representation. Create two lookup tables: one mapping question characters to numbers, and another for answer characters to number."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Creating a mapping from unique characters to indices\n",
    "token_index = dict([(char, i) for i, char in enumerate(tokens)])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'\\t': 0,\n",
       " '\\n': 1,\n",
       " ' ': 2,\n",
       " '(': 3,\n",
       " ')': 4,\n",
       " '*': 5,\n",
       " '+': 6,\n",
       " ',': 7,\n",
       " '-': 8,\n",
       " '.': 9,\n",
       " '/': 10,\n",
       " '0': 11,\n",
       " '1': 12,\n",
       " '2': 13,\n",
       " '3': 14,\n",
       " '4': 15,\n",
       " '5': 16,\n",
       " '6': 17,\n",
       " '7': 18,\n",
       " '8': 19,\n",
       " '9': 20,\n",
       " '?': 21,\n",
       " 'A': 22,\n",
       " 'C': 23,\n",
       " 'D': 24,\n",
       " 'E': 25,\n",
       " 'I': 26,\n",
       " 'M': 27,\n",
       " 'P': 28,\n",
       " 'S': 29,\n",
       " 'T': 30,\n",
       " 'W': 31,\n",
       " 'a': 32,\n",
       " 'b': 33,\n",
       " 'c': 34,\n",
       " 'd': 35,\n",
       " 'e': 36,\n",
       " 'f': 37,\n",
       " 'g': 38,\n",
       " 'h': 39,\n",
       " 'i': 40,\n",
       " 'k': 41,\n",
       " 'l': 42,\n",
       " 'm': 43,\n",
       " 'n': 44,\n",
       " 'o': 45,\n",
       " 'p': 46,\n",
       " 'q': 47,\n",
       " 'r': 48,\n",
       " 's': 49,\n",
       " 't': 50,\n",
       " 'u': 51,\n",
       " 'v': 52,\n",
       " 'w': 53,\n",
       " 'x': 54,\n",
       " 'y': 55}"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "token_index"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create keras data generator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Parameters\n",
    "params = {'batch_size': settings_dict[\"batch_size\"],\n",
    "          'max_seq_length': max_seq_length,\n",
    "          'num_tokens': num_tokens,\n",
    "          'token_index': token_index,\n",
    "          'num_thinking_steps': settings_dict[\"thinking_steps\"]\n",
    "         }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [],
   "source": [
    "training_generator = DataGeneratorSeq(input_texts=input_texts_train, target_texts=target_texts_train, **params)\n",
    "validation_generator = DataGeneratorSeq(input_texts=input_texts_valid, target_texts=target_texts_valid, **params)\n",
    "interpolate_generator = DataGeneratorSeq(input_texts=input_texts['interpolate'], target_texts=target_texts['interpolate'], **params)\n",
    "extrapolate_generator = DataGeneratorSeq(input_texts=input_texts['extrapolate'], target_texts=target_texts['extrapolate'], **params)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [],
   "source": [
    "a,b = training_generator.__getitem__(1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Train model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [],
   "source": [
    "valid_dict = {\n",
    "    'validation':validation_generator,\n",
    "    'interpolation': interpolate_generator,\n",
    "    'extrapolation': extrapolate_generator\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [],
   "source": [
    "history = NValidationSetsCallback(valid_dict)\n",
    "gradient = GradientLogger(live_metrics=['loss', 'exact_match_metric'], live_gaps=10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [],
   "source": [
    "epochs = settings_dict['epochs']  # Number of epochs to train for.\n",
    "latent_dim = settings_dict['latent_dim']  # Latent dimensionality of the encoding space."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [],
   "source": [
    "lstm = LSTM_Simple(num_tokens, latent_dim)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = lstm.get_model()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"model\"\n",
      "_________________________________________________________________\n",
      "Layer (type)                 Output Shape              Param #   \n",
      "=================================================================\n",
      "input_1 (InputLayer)         [(None, None, 56)]        0         \n",
      "_________________________________________________________________\n",
      "cu_dnnlstm (CuDNNLSTM)       [(None, None, 2048), (Non 17252352  \n",
      "_________________________________________________________________\n",
      "dense (Dense)                (None, None, 56)          114744    \n",
      "=================================================================\n",
      "Total params: 17,367,096\n",
      "Trainable params: 17,367,096\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n"
     ]
    }
   ],
   "source": [
    "model.summary()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "start training...\n",
      "  22/4687 [..............................] - ETA: 3:24:50 - loss: 0.0863 - exact_match_metric: 0.0017"
     ]
    },
    {
     "ename": "KeyboardInterrupt",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mKeyboardInterrupt\u001b[0m                         Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-58-aa1bbe551923>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      6\u001b[0m                                  \u001b[0mepochs\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mepochs\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      7\u001b[0m                                  \u001b[0mcallbacks\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mhistory\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;31m#, gradient],\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 8\u001b[0;31m                                  \u001b[0mverbose\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      9\u001b[0m                                 )\n",
      "\u001b[0;32m/usr/local/lib/python3.5/dist-packages/tensorflow/python/keras/engine/training.py\u001b[0m in \u001b[0;36mfit_generator\u001b[0;34m(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, validation_freq, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)\u001b[0m\n\u001b[1;32m   1513\u001b[0m         \u001b[0mshuffle\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mshuffle\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1514\u001b[0m         \u001b[0minitial_epoch\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0minitial_epoch\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1515\u001b[0;31m         steps_name='steps_per_epoch')\n\u001b[0m\u001b[1;32m   1516\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1517\u001b[0m   def evaluate_generator(self,\n",
      "\u001b[0;32m/usr/local/lib/python3.5/dist-packages/tensorflow/python/keras/engine/training_generator.py\u001b[0m in \u001b[0;36mmodel_iteration\u001b[0;34m(model, data, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, validation_freq, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch, mode, batch_size, steps_name, **kwargs)\u001b[0m\n\u001b[1;32m    255\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    256\u001b[0m       \u001b[0mis_deferred\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mmodel\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_is_compiled\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 257\u001b[0;31m       \u001b[0mbatch_outs\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mbatch_function\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0mbatch_data\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    258\u001b[0m       \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0misinstance\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mbatch_outs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mlist\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    259\u001b[0m         \u001b[0mbatch_outs\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0mbatch_outs\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/usr/local/lib/python3.5/dist-packages/tensorflow/python/keras/engine/training.py\u001b[0m in \u001b[0;36mtrain_on_batch\u001b[0;34m(self, x, y, sample_weight, class_weight, reset_metrics)\u001b[0m\n\u001b[1;32m   1257\u001b[0m       \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1258\u001b[0m         \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_make_fit_function\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1259\u001b[0;31m         \u001b[0moutputs\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_fit_function\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mins\u001b[0m\u001b[0;34m)\u001b[0m  \u001b[0;31m# pylint: disable=not-callable\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   1260\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1261\u001b[0m     \u001b[0;32mif\u001b[0m \u001b[0mreset_metrics\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/usr/local/lib/python3.5/dist-packages/tensorflow/python/keras/backend.py\u001b[0m in \u001b[0;36m__call__\u001b[0;34m(self, inputs)\u001b[0m\n\u001b[1;32m   3215\u001b[0m         \u001b[0mvalue\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmath_ops\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcast\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mvalue\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtensor\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdtype\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   3216\u001b[0m       \u001b[0mconverted_inputs\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mappend\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mvalue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 3217\u001b[0;31m     \u001b[0moutputs\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_graph_fn\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0mconverted_inputs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   3218\u001b[0m     return nest.pack_sequence_as(self._outputs_structure,\n\u001b[1;32m   3219\u001b[0m                                  [x.numpy() for x in outputs])\n",
      "\u001b[0;32m/usr/local/lib/python3.5/dist-packages/tensorflow/python/eager/function.py\u001b[0m in \u001b[0;36m__call__\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m    556\u001b[0m       raise TypeError(\"Keyword arguments {} unknown. Expected {}.\".format(\n\u001b[1;32m    557\u001b[0m           list(kwargs.keys()), list(self._arg_keywords)))\n\u001b[0;32m--> 558\u001b[0;31m     \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_call_flat\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    559\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    560\u001b[0m   \u001b[0;32mdef\u001b[0m \u001b[0m_filtered_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/usr/local/lib/python3.5/dist-packages/tensorflow/python/eager/function.py\u001b[0m in \u001b[0;36m_call_flat\u001b[0;34m(self, args)\u001b[0m\n\u001b[1;32m    625\u001b[0m     \u001b[0;31m# Only need to override the gradient in graph mode and when we have outputs.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    626\u001b[0m     \u001b[0;32mif\u001b[0m \u001b[0mcontext\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mexecuting_eagerly\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0moutputs\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 627\u001b[0;31m       \u001b[0moutputs\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_inference_function\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcall\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mctx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0margs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    628\u001b[0m     \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    629\u001b[0m       \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_register_gradient\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/usr/local/lib/python3.5/dist-packages/tensorflow/python/eager/function.py\u001b[0m in \u001b[0;36mcall\u001b[0;34m(self, ctx, args)\u001b[0m\n\u001b[1;32m    413\u001b[0m             attrs=(\"executor_type\", executor_type,\n\u001b[1;32m    414\u001b[0m                    \"config_proto\", config),\n\u001b[0;32m--> 415\u001b[0;31m             ctx=ctx)\n\u001b[0m\u001b[1;32m    416\u001b[0m       \u001b[0;31m# Replace empty list with None\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    417\u001b[0m       \u001b[0moutputs\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0moutputs\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/usr/local/lib/python3.5/dist-packages/tensorflow/python/eager/execute.py\u001b[0m in \u001b[0;36mquick_execute\u001b[0;34m(op_name, num_outputs, inputs, attrs, ctx, name)\u001b[0m\n\u001b[1;32m     58\u001b[0m     tensors = pywrap_tensorflow.TFE_Py_Execute(ctx._handle, device_name,\n\u001b[1;32m     59\u001b[0m                                                \u001b[0mop_name\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minputs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mattrs\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 60\u001b[0;31m                                                num_outputs)\n\u001b[0m\u001b[1;32m     61\u001b[0m   \u001b[0;32mexcept\u001b[0m \u001b[0mcore\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_NotOkStatusException\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0me\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     62\u001b[0m     \u001b[0;32mif\u001b[0m \u001b[0mname\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mKeyboardInterrupt\u001b[0m: "
     ]
    }
   ],
   "source": [
    "adam = Adam(lr=6e-4, beta_1=0.9, beta_2=0.995, epsilon=1e-9, decay=0.0, amsgrad=False, clipnorm=0.1)\n",
    "\n",
    "model.compile(optimizer=adam, loss='categorical_crossentropy', metrics=[exact_match_metric])\n",
    "print('start training...')\n",
    "train_hist = model.fit_generator(training_generator,\n",
    "                                 epochs=epochs,\n",
    "                                 callbacks=[history],#, gradient],\n",
    "                                 verbose=1,\n",
    "                                )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (<ipython-input-1-aabe21b7fb28>, line 13)",
     "output_type": "error",
     "traceback": [
      "\u001b[0;36m  File \u001b[0;32m\"<ipython-input-1-aabe21b7fb28>\"\u001b[0;36m, line \u001b[0;32m13\u001b[0m\n\u001b[0;31m    +)\u001b[0m\n\u001b[0m     ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "plt.plot(train_hist.history['loss'],color='C0', label='train')\n",
    "plt.plot(train_hist.history['validation_loss'], color='C0', label='valid', linestyle='--')\n",
    "plt.plot(train_hist.history['extrapolation_loss'], color='C1', label='extra',)\n",
    "plt.plot(train_hist.history['interpolation_loss'], color='C2', label='inter')\n",
    "\n",
    "plt.xlabel('epochs')\n",
    "plt.ylabel('loss')\n",
    "plt.legend(loc='best')\n",
    "plt.ylim([0,1])\n",
    "plt.grid(True, linestyle='--')\n",
    "plt.tight_layout()\n",
    "plt.savefig(settings_dict['save_path'] + 'losses.png', dpi=300)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(train_hist.history['exact_match_metric'],color='C0', label='train')\n",
    "plt.plot(train_hist.history['validation_exact_match_metric'], color='C0', label='valid', linestyle='--')\n",
    "plt.plot(train_hist.history['extrapolation_exact_match_metric'], color='C1', label='extra',)\n",
    "plt.plot(train_hist.history['interpolation_exact_match_metric'], color='C2', label='inter')\n",
    "\n",
    "plt.xlabel('epochs')\n",
    "plt.ylabel('exact match metric')\n",
    "plt.legend(loc='best')\n",
    "plt.ylim([0,1])\n",
    "plt.grid(True, linestyle='--')\n",
    "plt.tight_layout()\n",
    "plt.savefig(settings_dict['save_path'] + 'metrics.png', dpi=300)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(settings_dict['save_path']+'experiments_output.pkl','wb') as file:\n",
    "    pickle.dump(train_hist.history, file)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.save(settings_dict['save_path']+'this_model.model')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "metadata": {},
   "outputs": [
    {
     "ename": "FileNotFoundError",
     "evalue": "[Errno 2] No such file or directory: '../../artifacts/settings.json'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mFileNotFoundError\u001b[0m                         Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-78-073251a7b242>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'../..'\u001b[0m\u001b[0;34m+\u001b[0m\u001b[0msettings_dict\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'save_path'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m+\u001b[0m\u001b[0;34m'settings.json'\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m'wb'\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mfile\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      2\u001b[0m     \u001b[0mjson\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdump\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msettings_dict\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfile\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: '../../artifacts/settings.json'"
     ]
    }
   ],
   "source": [
    "with open(settings_dict['save_path']+'settings.json','w') as file:\n",
    "    json.dump(settings_dict, file)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
